package com.chungkui.ratelimiter.impl;

import com.chungkui.ratelimiter.RateLimiterCache;
import com.chungkui.ratelimiter.StandAloneRateLimiter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jason
 * @Date: 2020/1/11 18:34
 * @Version 1.0
 */
public class RateLimiterCacheImpl implements RateLimiterCache {

    private Cache<String, StandAloneRateLimiter> caches;
    private int capacity = 1000;
    private int maximumSize = 100000;
    private long cacheExpireSeconds = 300;
    private Cache<String, StandAloneRateLimiter> dynamicCaches;

    @PostConstruct
    public void init() {
        caches = CacheBuilder.newBuilder().expireAfterWrite(cacheExpireSeconds, TimeUnit.SECONDS)
                .initialCapacity(capacity)
                .maximumSize(maximumSize)
                .build();
        dynamicCaches = CacheBuilder.newBuilder().expireAfterWrite(120, TimeUnit.SECONDS)
                .initialCapacity(capacity)
                .maximumSize(maximumSize)
                .build();
    }


    @Override
    public StandAloneRateLimiter get(String key) {
        return caches.getIfPresent(key);
    }

    @Override
    public StandAloneRateLimiter getDynamic(String key) {
        return dynamicCaches.getIfPresent(key);
    }

    @Override
    public void setDynamic(String key, StandAloneRateLimiter val) {
        dynamicCaches.put(key, val);
    }

    @Override
    public void set(String key, StandAloneRateLimiter val) {
        caches.put(key, val);
    }

    @Override
    public void clear() {
        caches.invalidateAll();
        dynamicCaches.invalidateAll();
    }


}
